﻿-- 1) Cuando saco un destinatario a un álbum, debería quitar ese destinatario de todas las fotos del álbum.
CREATE OR REPLACE FUNCTION borrar_destinatario() RETURNS TRIGGER AS $borrar_destinatario$
	BEGIN
		IF (TG_NAME = 'borrar_destinatario_persona') THEN
				DELETE FROM destinatario_usuario
				WHERE publicacion IN (SELECT id
						FROM foto as F
						WHERE OLD.publicacion = F.album);
		ELSEIF (TG_NAME = 'borrar_destinatario_circulo') THEN
				DELETE FROM destinatario_circulo
				WHERE publicacion in (SELECT id
						FROM foto as F
						WHERE OLD.publicacion = F.album);
		END IF;
		RETURN NULL;
	END;
$borrar_destinatario$ LANGUAGE plpgsql;

CREATE TRIGGER borrar_destinatario_persona AFTER DELETE
	ON destinatario_usuario FOR EACH ROW 
	EXECUTE PROCEDURE borrar_destinatario();

CREATE TRIGGER borrar_destinatario_circulo AFTER DELETE 
	ON destinatario_circulo FOR EACH ROW 
	EXECUTE PROCEDURE borrar_destinatario();